<?php

namespace App\Utils;

use App\Exception\RateLimitedException;
use App\Pool\Redis\DefaultPool;
use Hyperf\Di\Annotation\Inject;

trait LockTraits
{

    #[Inject]
    protected DefaultPool $lockPool;

    public function lock($key, $sec=60)
    {
        return $this->lockPool->set($key,'1',['NX','EX'=>$sec,]);
    }

    /**
     * @param string $key
     * @param int $sec
     * @return void
     * @throws RateLimitedException
     */
    public function lockError($key, $sec=60)
    {
        if (!$this->lock($key, $sec)){
            throw new RateLimitedException('操作太快了，稍后重试');
        }
    }

    public function freeLock($key)
    {
        return $this->lockPool->del($key);
    }
}